﻿using PC.PickleJar.Validators;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PC.PickleJar.Configuration
{
	public class ValidatorElement : ConfigurationElement
	{
		private ValidatorBase validatorInstance;

		[ConfigurationProperty("type", IsRequired = true)]
		public String Type
		{
			get
			{
				return (String)this["type"];
			}
			set
			{
				this["type"] = value;
			}
		}

		public ValidatorBase ValidatorInstance
		{
			get
			{
				try
				{
					if (this.validatorInstance == null)
					{
						var validator = (ValidatorBase)TypeInfo.GetType(this.Type, true).GetConstructor(System.Type.EmptyTypes).Invoke(null);
						this.validatorInstance = validator;
					}
					return this.validatorInstance;
				}
				catch (FileNotFoundException exception)
				{
					throw new InvalidOperationException(
						String.Format(
							CultureInfo.InvariantCulture,
							"Could not resolve validator of type \"{0}\".",
							this.Type),
							exception);
				}
			}
		}
	}
}
